import React, { useState } from "react";
import axios from "axios";

const Chat = () => {
  const [messages, setMessages] = useState([]); // 存储对话消息
  const [inputText, setInputText] = useState(""); // 用户输入的内容

  // DeepSeek API端点
  const API_URL = "https://api.deepseek.com/v1/ecommerce/chat";
  const API_KEY = "sk-b7a2f211595c49259f1b1f593268af4f"; // 替换为你的API密钥

  // 发送消息给AI客服
  const sendMessage = async () => {
    if (!inputText.trim()) return;

    // 将用户输入添加到消息列表
    const userMessage = { text: inputText, sender: "user" };
    setMessages((prevMessages) => [...prevMessages, userMessage]);
    setInputText("");

    try {
      // 调用DeepSeek API
      const response = await axios.post(
        API_URL,
        {
          message: inputText,
          user_id: "12345", // 替换为实际用户ID
        },
        {
          headers: {
            Authorization: `Bearer ${API_KEY}`,
            "Content-Type": "application/json",
          },
        }
      );

      // 将AI回复添加到消息列表
      const aiMessage = { text: response.data.reply, sender: "ai" };
      setMessages((prevMessages) => [...prevMessages, aiMessage]);
    } catch (error) {
      console.error("Error sending message:", error);
      // 显示错误信息
      const errorMessage = { text: "Failed to get response from AI.", sender: "error" };
      setMessages((prevMessages) => [...prevMessages, errorMessage]);
    }
  };

  return (
    <div style={styles.chatContainer}>
      <div style={styles.messagesContainer}>
        {messages.map((msg, index) => (
          <div key={index} style={msg.sender === "user" ? styles.userMessage : styles.aiMessage}>
            {msg.text}
          </div>
        ))}
      </div>
      <div style={styles.inputContainer}>
        <input
          type="text"
          value={inputText}
          onChange={(e) => setInputText(e.target.value)}
          onKeyPress={(e) => e.key === "Enter" && sendMessage()}
          style={styles.input}
          placeholder="Type your message..."
        />
        <button onClick={sendMessage} style={styles.button}>
          Send
        </button>
      </div>
    </div>
  );
};

// 简单样式
const styles = {
  chatContainer: {
    width: "400px",
    margin: "0 auto",
    padding: "20px",
    border: "1px solid #ccc",
    borderRadius: "10px",
  },
  messagesContainer: {
    height: "300px",
    overflowY: "auto",
    marginBottom: "10px",
    borderBottom: "1px solid #ccc",
  },
  userMessage: {
    textAlign: "right",
    color: "blue",
    margin: "5px 0",
  },
  aiMessage: {
    textAlign: "left",
    color: "green",
    margin: "5px 0",
  },
  inputContainer: {
    display: "flex",
  },
  input: {
    flex: 1,
    padding: "10px",
    borderRadius: "5px",
    border: "1px solid #ccc",
  },
  button: {
    marginLeft: "10px",
    padding: "10px 20px",
    borderRadius: "5px",
    border: "none",
    backgroundColor: "#007bff",
    color: "#fff",
    cursor: "pointer",
  },
};

export default Chat;